package com.douyin.config;

import java.nio.charset.StandardCharsets;

import com.douyin.entity.ApiLog;
import com.douyin.service.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingInterceptor.class);

    private final LogService logService;

    public RequestLoggingInterceptor(LogService logService) {
        this.logService = logService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        try {
            long startTime = (Long) request.getAttribute("startTime");
            long duration = System.currentTimeMillis() - startTime;

            String requestBody = "";
            String responseBody = "";

            if (request instanceof ContentCachingRequestWrapper) {
                requestBody = new String(
                        ((ContentCachingRequestWrapper) request).getContentAsByteArray(),
                        StandardCharsets.UTF_8
                );
            }

            if (response instanceof ContentCachingResponseWrapper) {
                responseBody = new String(
                        ((ContentCachingResponseWrapper) response).getContentAsByteArray(),
                        StandardCharsets.UTF_8
                );
                ((ContentCachingResponseWrapper) response).copyBodyToResponse();
            }

            // 创建日志对象
            ApiLog log = new ApiLog(
                    request.getMethod(),
                    request.getRequestURI(),
                    requestBody,
                    response.getStatus(),
                    responseBody,
                    duration
            );

            // 记录日志
            logService.logRequest(log);

        } catch (Exception e) {
            logger.error("Error logging request", e);
        }
    }
}
